package com.duan.service.impl;

import com.duan.service.UploadDownloadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author db
 * @version 1.0
 * @description uploadDownloadServiceImpl
 * @since 2023/8/17
 */

@Service
@Slf4j
public class UploadDownloadServiceImpl implements UploadDownloadService {


    /**
     * 上传文件要考虑的细节
     *     1、如何修改文件上传时文件名    UUID+文件后缀
     *     2、上传的文件放在当前日期的目录中
     *     3、考虑上传文件的大小限制
     * @param file
     */
    @Override
    public void uploadDocument(MultipartFile file) {


        // 要上传的文件存放的地址
        String path = "D:\\test\\";

        // 获得文件名称
        String name = file.getName();
        log.info("name {}",name);

        String originalFilename = file.getOriginalFilename();
        log.info("originalFilename {}",originalFilename);

        // 新文件名称
        String newFileName = UUID.randomUUID().toString().replace("-","") + originalFilename;

        // 以当前日期为文件夹名称，新建文件夹
        String currentDay = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        // 存放上传文件的目录
        File newFile = new File(path,currentDay);
        if(!newFile.exists()){
            newFile.mkdirs();
        }
        try{
            file.transferTo(new File(newFile,newFileName));
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    @Override
    public void download(String filePath, HttpServletResponse response) {
        // 1、从指定目录中读取文件
        File file = new File(filePath);

        BufferedInputStream is = null;
        ServletOutputStream os = null;
        try{
            // 2、将文件读取为文件输入流
            is= new BufferedInputStream(new FileInputStream(file));

            String fileName = file.getName();

            // 获得响应流之前，设置文件以附件形式下载 attachment
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
            // 3、获取输出流

            os = response.getOutputStream();

            // 4、输入流复制给输出流
            int len=0;
            byte[] b = new byte[1024];
            while((len=is.read(b)) != -1){
                os.write(b,0,len);
            }
        }catch (Exception e){

        }finally {
            // 4. 关闭资源(如果有多个流，我们需要先关闭外面的流，再关闭内部的流)
            try {
                if (os != null)
                    os.close();
            } catch (IOException e) {
                log.error("关闭输出流失败");
            }
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                log.error("关闭输入流失败");
            }
        }


    }

    @Override
    public void downloadFromURL(String urlAddress, String savePath)  {

        // 获得文件名称
        String[] split = urlAddress.split("/");
        String fileName = split[split.length -1];

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try{
            URL url = new URL(urlAddress);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod(con.getRequestMethod());
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("User-Agent", "Mozilla/4.76");
            con.setRequestProperty("connection", "keep-alive");
            con.setDoOutput(true);

            // 将文件读取为文件输入流
            bis = new BufferedInputStream(con.getInputStream());

            // 文件输出流
            bos = new BufferedOutputStream(new FileOutputStream(savePath+fileName));

            // 3. 输入流复制给输出流
            int len=0;
            byte[] b = new byte[1024];
            while((len=bis.read(b)) != -1){
                bos.write(b,0,len);
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }finally {
            // 4. 关闭资源(如果有多个流，我们需要先关闭外面的流，再关闭内部的流)
            try {
                if (bos != null)
                    bos.close();
            } catch (IOException e) {
                log.error("关闭输出流失败");
            }
            try {
                if (bis != null)
                    bis.close();
            } catch (IOException e) {
                log.error("关闭输入流失败");
            }
        }

    }
}
